use crate::{AppState, BandwidthLevel, BandwidthStatus, NetworkStats, SystemInfo};
use local_ip_address::local_ip;
use serde_json;
use std::sync::atomic::Ordering;

#[allow(unused_imports)]
use tauri::{Emitter, State};

#[tauri::command]
pub async fn start_bandwidth_consumption(
    level: BandwidthLevel,
    state: State<'_, AppState>,
    app_handle: tauri::AppHandle,
) -> Result<(), String> {
    println!("启动带宽占用，等级: {:?}", level);

    state.is_running.store(true, Ordering::SeqCst);
    let controller_arc = state.bandwidth_controller.clone();

    tauri::async_runtime::spawn(async move {
        let mut controller = controller_arc.write().await;
        controller.set_app_handle(app_handle);

        if let Err(e) = controller.start(level).await {
            eprintln!("Failed to start bandwidth consumption: {}", e);
        }
    });

    Ok(())
}

#[tauri::command]
pub async fn stop_bandwidth_consumption(state: State<'_, AppState>) -> Result<(), String> {
    println!("停止带宽占用");

    state.is_running.store(false, Ordering::SeqCst);
    let controller_arc = state.bandwidth_controller.clone();

    tauri::async_runtime::spawn(async move {
        let mut controller = controller_arc.write().await;
        controller.stop().await;
    });

    Ok(())
}

#[tauri::command]
pub async fn get_bandwidth_status(state: State<'_, AppState>) -> Result<BandwidthStatus, String> {
    let controller = state.bandwidth_controller.read().await;
    let is_running = state.is_running.load(Ordering::SeqCst);

    Ok(controller.get_status(is_running))
}

#[tauri::command]
pub async fn get_system_info(state: State<'_, AppState>) -> Result<SystemInfo, String> {
    let mut system = state.system.lock().await;
    // 先刷新CPU信息获取准确的使用率
    system.refresh_cpu_usage();
    system.refresh_memory();

    // 获取IP地址
    let ip_address = match local_ip() {
        Ok(ip) => ip.to_string(),
        Err(_) => "未知".to_string(),
    };

    // 获取CPU使用率
    let cpu_usage = if system.cpus().is_empty() {
        0.0
    } else {
        system
            .cpus()
            .iter()
            .map(|cpu| cpu.cpu_usage() as f64)
            .sum::<f64>()
            / system.cpus().len() as f64
    };

    // 获取内存使用率
    let memory_usage = if system.total_memory() > 0 {
        (system.used_memory() as f64 / system.total_memory() as f64) * 100.0
    } else {
        0.0
    };

    // 获取网络接口信息 (简化版)
    let network_interface = "WiFi".to_string();

    Ok(SystemInfo {
        ip_address,
        network_type: "WiFi".to_string(),
        connection_status: "已连接".to_string(),
        cpu_usage,
        memory_usage,
        network_interface,
    })
}

#[tauri::command]
pub async fn get_network_stats(state: State<'_, AppState>) -> Result<NetworkStats, String> {
    let controller = state.bandwidth_controller.read().await;
    let status = controller.get_status(state.is_running.load(Ordering::SeqCst));

    // 基于当前状态计算统计数据
    let current_speed = status.current_speed_mbps;
    let _peak_speed = current_speed * 1.2; // 模拟峰值速度
    let efficiency = if current_speed > 0.0 { 85.0 } else { 0.0 }; // 模拟效率

    let mut stats = state.network_stats.lock().await;

    // 更新统计数据
    if current_speed > stats.peak_speed {
        stats.peak_speed = current_speed;
    }

    stats.average_speed = current_speed;
    stats.efficiency = efficiency;
    stats.run_count += if state.is_running.load(Ordering::SeqCst) {
        1
    } else {
        0
    };
    stats.avg_session_time = (status.duration_seconds / 60) as u32; // 转换为分钟
    stats.weekly_run_time = status.duration_seconds as f64 / 3600.0; // 转换为小时
    stats.weekly_data_usage = status.bytes_consumed as f64 / 1_000_000_000.0; // 转换为GB

    Ok(stats.clone())
}

#[tauri::command]
pub async fn get_available_bandwidth_levels() -> Result<Vec<BandwidthLevel>, String> {
    Ok(vec![
        BandwidthLevel::Off,
        BandwidthLevel::Micro,
        BandwidthLevel::Mini,
        BandwidthLevel::Low,
        BandwidthLevel::Medium,
        BandwidthLevel::High,
        BandwidthLevel::Turbo,
        BandwidthLevel::Ultra,
        BandwidthLevel::Extreme,
    ])
}

#[tauri::command]
pub fn get_bandwidth_level_info(level: BandwidthLevel) -> Result<serde_json::Value, String> {
    let info = match level {
        BandwidthLevel::Off => serde_json::json!({
            "name": "关闭",
            "description": "停止占用带宽",
            "speed_mbps": 0,
            "color": "#6b7280"
        }),
        BandwidthLevel::Micro => serde_json::json!({
            "name": "微速",
            "description": "占用 5 Mbps 带宽",
            "speed_mbps": 5,
            "color": "#84cc16"
        }),
        BandwidthLevel::Mini => serde_json::json!({
            "name": "慢速",
            "description": "占用 15 Mbps 带宽",
            "speed_mbps": 15,
            "color": "#22c55e"
        }),
        BandwidthLevel::Low => serde_json::json!({
            "name": "轻度",
            "description": "占用 30 Mbps 带宽",
            "speed_mbps": 30,
            "color": "#10b981"
        }),
        BandwidthLevel::Medium => serde_json::json!({
            "name": "中度",
            "description": "占用 50 Mbps 带宽",
            "speed_mbps": 50,
            "color": "#f59e0b"
        }),
        BandwidthLevel::High => serde_json::json!({
            "name": "高速",
            "description": "占用 75 Mbps 带宽",
            "speed_mbps": 75,
            "color": "#f97316"
        }),
        BandwidthLevel::Turbo => serde_json::json!({
            "name": "涡轮",
            "description": "占用 100 Mbps 带宽",
            "speed_mbps": 100,
            "color": "#e11d48"
        }),
        BandwidthLevel::Ultra => serde_json::json!({
            "name": "超速",
            "description": "占用 150 Mbps 带宽",
            "speed_mbps": 150,
            "color": "#dc2626"
        }),
        BandwidthLevel::Extreme => serde_json::json!({
            "name": "极限",
            "description": "占用 200 Mbps 带宽",
            "speed_mbps": 200,
            "color": "#ef4444"
        }),
    };

    Ok(info)
}

// Android独有的命令
#[cfg(target_os = "android")]
#[tauri::command]
pub fn init_mobile() {
    std::env::set_var("RUST_BACKTRACE", "1");
}

// 退出应用命令
#[tauri::command]
pub async fn exit_app(app_handle: tauri::AppHandle) -> Result<(), String> {
    println!("正在退出应用...");
    app_handle.exit(0);
    Ok(())
}

// 阻止默认退出行为的命令（用于移动端）
#[cfg(target_os = "android")]
#[tauri::command]
pub async fn prevent_default_exit() -> Result<(), String> {
    // 在Android上，这个命令用来表示我们已经处理了返回键事件
    // 实际的退出逻辑由前端的确认对话框控制
    println!("阻止默认退出行为");
    Ok(())
}

// 触发返回键事件的命令（用于移动端）
#[cfg(target_os = "android")]
#[tauri::command]
pub async fn handle_back_button(app_handle: tauri::AppHandle) -> Result<(), String> {
    // 发出自定义事件给前端
    app_handle
        .emit("android-back-button", ())
        .map_err(|e| e.to_string())?;
    println!("已发出返回键事件");
    Ok(())
}

// 检查当前平台的命令
#[tauri::command]
pub fn get_platform_info() -> Result<serde_json::Value, String> {
    let platform_info = serde_json::json!({
        "platform": std::env::consts::OS,
        "arch": std::env::consts::ARCH,
        "is_mobile": cfg!(target_os = "android") || cfg!(target_os = "ios")
    });

    Ok(platform_info)
}
